<?php

namespace app\admin\controller;

use app\admin\service\CityService;
use app\model\system\SetCity;
use support\Request;
use support\View;

class CityController extends Curd
{

    /**
     * 获取列表
     */
    public function index(Request $request)
    {
        $pid = $request->input('pid', 0);
        $level = $request->input('level', 0);
        $where[] = ['pid', '=', $pid];
        $cityService = new CityService();
        $res = $cityService->getList($where, $level);
        if (request()->isAjax()) {
            return $this->json(0, 'success', toArray($res['data']));
        }
        View::assign([
            'tree' => $res['data']
        ]);

        return view('city/index');
    }

    /**
     * 添加
     */
    public function add(Request  $request)
    {
        if (request()->isAjax()) {

            $param = $request->post();

            $cityService = new CityService();
            $res = $cityService->addCity($param);
            return $this->success($res);
        }

        return view('city/add');
    }

    /**
     * 编辑
     */
    public function edit(Request  $request)
    {
        if (request()->isAjax()) {

            $param = $request->post();

            $cityService = new CityService();
            $res = $cityService->editCity($param);
            return $this->success($res);
        }

        $id = $request->input('id');
        $setCityModel = new SetCity();
        View::assign([
            'info' => $setCityModel->findOne([
                'id' => $id
            ])['data']
        ]);

        return view('city/edit');
    }

    /**
     * 删除
     */
    public function del(Request $request)
    {
        $id = $request->input('id');

        $setCityModel = new SetCity();

        $has = $setCityModel->where('pid', $id)->first();
        if (!empty($has)) {
            return $this->json(-1, '该地区下还存在地区，不可删除');
        }
        $info = $setCityModel->delById($id);

         return $this->success($info);
    }
    /**
     * 获取所有的区域
     */
    public function area()
    {
        $cityService = new CityService();
        $res = $cityService->getAreaTree();

        return json($res);
    }
}